from PyCmpltrtok.common import get_dir_name_ext
import os

NO_MEDIA_FILE_NAME = '.nomedia'


def check_dir_pic_exts(xdir):
    xset = set()
    xdict = {
        'n_dir': 0,
        'n_file': 0,
    }
    _check_dir_pic_exts(xset, xdir, xdict)
    print()
    xresult = sorted(xset)
    print(xresult)
    return xresult


def _check_dir_pic_exts(xset_ref, xdir, stat_ref):

    def print_stat():
        print(f'\rdirs={stat_ref["n_dir"]}, files={stat_ref["n_file"]}', end='', flush=True)

    stat_ref["n_dir"] += 1
    print_stat()
    xitems = os.listdir(xdir)
    xpaths = [os.path.join(xdir, xitem) for xitem in xitems if xitem != NO_MEDIA_FILE_NAME]
    for xpath in xpaths:
        if os.path.isfile(xpath):
            _, _, xext = get_dir_name_ext(xpath)
            stat_ref["n_file"] += 1
            print_stat()
            xset_ref.add(xext.lower())
    for xpath in xpaths:
        if os.path.isdir(xpath):
            _check_dir_pic_exts(xset_ref, xpath, stat_ref)


if '__main__' == __name__:
    import argparse

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('target_dir', help='The target directory to check.')
    args = parser.parse_args()

    target_dir = args.target_dir
    check_dir_pic_exts(target_dir)
